package com.yc.snack.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class BaseController extends HttpServlet{
	private static final long serialVersionUID = -3762450955193187022L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getRequestURI();	//	/<项目名>/<servlet>/<method>	/snack/admin/login
		String methodName = url.substring(url.lastIndexOf("/") + 1);
		
		//要获取当前对象中的所有的方法，看是否有这个方法
		Method[] methods = this.getClass().getDeclaredMethods();
		
		for(Method method : methods) {
			if(methodName.equals(method.getName())) {	//如果我要的方法名跟当前循环的方法名一致，这说明我要调用的就是这个方法
				try {
					method.invoke(this, request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		}
		//如果没有找到对应的处理的方法，则报错404或405
		this.error(request, response);
	}

	private void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter(); 
		//request.getContextPath();	//获取到的就是访问的项目	/snack
		String basepath = request.getScheme() + "://" + request.getServerName() + ":" 
				+ request.getServerPort() + request.getContextPath() + "/";
		out.print("<script>alert('不支持的请求...');location.href='" + basepath + "index.html';</script>");
		out.flush();
		out.close();
	}
	
	protected void send(HttpServletResponse response, int code, String msg, Object data) throws IOException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out = response.getWriter();
		Gson gson = new GsonBuilder().serializeNulls().create();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", code);
		map.put("msg", msg);
		map.put("data", data);
		out.print(gson.toJson(map));
		out.flush();
	}
	
	protected void send(HttpServletResponse response, Object data) throws IOException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out = response.getWriter();
		Gson gson = new GsonBuilder().serializeNulls().create();
		out.print(gson.toJson(data));
		out.flush();
	}
	
	protected void send(HttpServletResponse response, int code, Object data) throws IOException {
		this.send(response, code, "", data);
	}
	
	protected void send(HttpServletResponse response, int code,String msg) throws IOException {
		this.send(response, code, msg, null);
	}
}

